package com.campus.help.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.common.Result;
import com.campus.help.entity.Secondhand;
import com.campus.help.entity.SecondhandType;
import com.campus.help.service.SecondhandService;
import com.campus.help.utils.JwtUtils;
import com.campus.help.vo.SecondhandVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * 二手商品控制器
 *
 * @author campus-help
 * @since 2025-10-16
 */
@Slf4j
@RestController
@RequestMapping("/secondhand")
public class SecondhandController {

    @Autowired
    private SecondhandService secondhandService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private com.campus.help.mapper.StudentMapper studentMapper;

    /**
     * 获取二手商品列表
     */
    @GetMapping("/list")
    public Result<Page<SecondhandVO>> getSecondhandList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false, defaultValue = "") String keyword,
            @RequestParam(required = false) Long typeId,
            @RequestParam(required = false, defaultValue = "") String location,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            @RequestParam(required = false, defaultValue = "") String condition,
            @RequestParam(required = false, defaultValue = "") String status,
            HttpServletRequest request) {

        try {
            // 从token中获取学生ID和学校ID
            String token = getTokenFromRequest(request);
            Long studentId = jwtUtils.getStudentIdFromToken(token);
            Long schoolId = getSchoolIdByStudentId(studentId);

            log.info("获取二手商品列表 - studentId: {}, schoolId: {}", studentId, schoolId);

            Page<SecondhandVO> secondhandList = secondhandService.getSecondhandList(
                    page, size, keyword, typeId, location, minPrice, maxPrice, condition, status, schoolId);
            return Result.success(secondhandList);
        } catch (Exception e) {
            log.error("获取二手商品列表失败", e);
            return Result.error("获取二手商品列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取二手商品详情
     */
    @GetMapping("/detail/{id}")
    public Result<SecondhandVO> getSecondhandDetail(@PathVariable Long id) {
        try {
            SecondhandVO detail = secondhandService.getSecondhandDetail(id);
            if (detail == null) {
                return Result.error("商品不存在");
            }

            // 增加浏览次数
            secondhandService.incrementViewCount(id);

            return Result.success(detail);
        } catch (Exception e) {
            log.error("获取二手商品详情失败", e);
            return Result.error("获取二手商品详情失败: " + e.getMessage());
        }
    }

    /**
     * 发布二手商品
     */
    @PostMapping("/publish")
    public Result<Secondhand> publishSecondhand(@RequestBody Secondhand secondhand, HttpServletRequest request) {
        try {
            // 从token中获取卖家ID和学校ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);
            Long schoolId = getSchoolIdByStudentId(sellerId);

            if (schoolId == null) {
                return Result.error("请先选择所在学校");
            }

            log.info("收到发布二手商品请求: sellerId={}, schoolId={}, title={}, typeId={}", 
                    sellerId, schoolId, secondhand.getTitle(), secondhand.getTypeId());

            Secondhand publishedSecondhand = secondhandService.publishSecondhand(secondhand, sellerId, schoolId);
            return Result.success("发布成功", publishedSecondhand);
        } catch (Exception e) {
            log.error("发布二手商品失败", e);
            return Result.error("发布二手商品失败: " + e.getMessage());
        }
    }

    /**
     * 更新二手商品
     */
    @PutMapping("/update")
    public Result<Secondhand> updateSecondhand(@RequestBody Secondhand secondhand, HttpServletRequest request) {
        try {
            // 从token中获取卖家ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);

            Secondhand updatedSecondhand = secondhandService.updateSecondhand(secondhand, sellerId);
            return Result.success("更新成功", updatedSecondhand);
        } catch (Exception e) {
            log.error("更新二手商品失败", e);
            return Result.error("更新二手商品失败: " + e.getMessage());
        }
    }

    /**
     * 删除二手商品
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteSecondhand(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 从token中获取卖家ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);

            boolean success = secondhandService.deleteSecondhand(id, sellerId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除二手商品失败", e);
            return Result.error("删除二手商品失败: " + e.getMessage());
        }
    }

    /**
     * 下架商品
     */
    @PostMapping("/off-shelf/{id}")
    public Result<String> offShelf(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 从token中获取卖家ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);

            boolean success = secondhandService.offShelf(id, sellerId);
            if (success) {
                return Result.success("下架成功");
            } else {
                return Result.error("下架失败");
            }
        } catch (Exception e) {
            log.error("下架商品失败", e);
            return Result.error("下架商品失败: " + e.getMessage());
        }
    }

    /**
     * 上架商品
     */
    @PostMapping("/on-shelf/{id}")
    public Result<String> onShelf(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 从token中获取卖家ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);

            boolean success = secondhandService.onShelf(id, sellerId);
            if (success) {
                return Result.success("上架成功");
            } else {
                return Result.error("上架失败");
            }
        } catch (Exception e) {
            log.error("上架商品失败", e);
            return Result.error("上架商品失败: " + e.getMessage());
        }
    }

    /**
     * 标记为已售出
     */
    @PostMapping("/mark-sold/{id}")
    public Result<String> markAsSold(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 从token中获取卖家ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);

            boolean success = secondhandService.markAsSold(id, sellerId);
            if (success) {
                return Result.success("标记成功");
            } else {
                return Result.error("标记失败");
            }
        } catch (Exception e) {
            log.error("标记商品失败", e);
            return Result.error("标记商品失败: " + e.getMessage());
        }
    }

    /**
     * 收藏商品
     */
    @PostMapping("/favorite/{id}")
    public Result<String> favoriteSecondhand(@PathVariable Long id) {
        try {
            secondhandService.incrementFavoriteCount(id);
            return Result.success("收藏成功");
        } catch (Exception e) {
            log.error("收藏商品失败", e);
            return Result.error("收藏商品失败: " + e.getMessage());
        }
    }

    /**
     * 取消收藏
     */
    @PostMapping("/unfavorite/{id}")
    public Result<String> unfavoriteSecondhand(@PathVariable Long id) {
        try {
            secondhandService.decrementFavoriteCount(id);
            return Result.success("取消收藏成功");
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return Result.error("取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 获取我发布的商品列表
     */
    @GetMapping("/my-published")
    public Result<Page<Secondhand>> getMyPublishedList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        try {
            // 从token中获取卖家ID
            String token = getTokenFromRequest(request);
            Long sellerId = jwtUtils.getStudentIdFromToken(token);

            Page<Secondhand> secondhandList = secondhandService.getMyPublishedList(sellerId, page, size);
            return Result.success(secondhandList);
        } catch (Exception e) {
            log.error("获取我发布的商品失败", e);
            return Result.error("获取我发布的商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取热门商品
     */
    @GetMapping("/hot")
    public Result<List<SecondhandVO>> getHotSecondhandList(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<SecondhandVO> hotList = secondhandService.getHotSecondhandList(limit);
            return Result.success(hotList);
        } catch (Exception e) {
            log.error("获取热门商品失败", e);
            return Result.error("获取热门商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有商品类型
     */
    @GetMapping("/types")
    public Result<List<SecondhandType>> getAllTypes() {
        try {
            List<SecondhandType> types = secondhandService.getAllTypes();
            return Result.success(types);
        } catch (Exception e) {
            log.error("获取商品类型失败", e);
            return Result.error("获取商品类型失败: " + e.getMessage());
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            return authorization.substring(7);
        }
        throw new RuntimeException("Token不能为空");
    }

    /**
     * 根据学生ID获取学校ID
     */
    private Long getSchoolIdByStudentId(Long studentId) {
        try {
            com.campus.help.entity.Student student = studentMapper.selectById(studentId);
            if (student == null) {
                throw new RuntimeException("学生不存在");
            }
            return student.getSchoolId();
        } catch (Exception e) {
            log.error("获取学生学校ID失败: studentId={}", studentId, e);
            throw new RuntimeException("获取学生学校ID失败: " + e.getMessage());
        }
    }
}

